<script setup>
import { ref, watch } from 'vue';
import './assets/style.css'; 
import TodoHeader from './components/TodoHeader.vue';
import TodoMain from './components/TodoMain.vue';
import TodoFooter from './components/TodoFooter.vue';

const todoList = ref(JSON.parse(localStorage.getItem('to-do-list-key')) || 
[
  { id: 321, name: '学Vue组件通信', finished: false },
  { id: 127, name: '打王者', finished: true },
  { id: 666, name: '跑步1小时', finished: false }
]);

const handleAdd = (title) => {
  const obj = {
    id:Date.now(),
    name:title,
    finished:false
  }
  todoList.value.push(obj)
}

const handleDel = (index) => {
  if(window.confirm('确认删除吗')) {
    todoList.value.splice(index,1)
  }
}

const clearCompleted = () => {
  todoList.value = todoList.value.filter((item) => {
    return !item.finished
  })
}


watch(
  todoList,
  (newVal) => {
  localStorage.setItem('to-do-list-key',JSON.stringify(newVal))},
  {deep:true})
</script>

<template>
  <section class="todoapp">
    <todo-header @add="handleAdd"/>
    <todo-main :todoList="todoList" @del="handleDel"/>
    <todo-footer :todoList="todoList" @clearCompleted="clearCompleted"/> 
  </section>
</template>